﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Dictionary
{
    public partial class CatalogDetails : Form
    {
        private Catalog _parent;
        private DIProject.DataSets.Dictionary.CatalogDataTable _catalogData;
        private DIProject.DataSets.Dictionary.CatalogDataTable CatalogData
        {
            get
            {
                if (_catalogData != null)
                    return _catalogData;
                return _parent.dictionary.Catalog;
            }
        }
        private DIProject.DataSets.Dictionary.CatalogRow _curRow;
        /// <summary>
        /// выбранная строка в таблице фармгрупп
        /// </summary>
        public DIProject.DataSets.Dictionary.CatalogRow CurrentRow
        {
            get { return _curRow; }
            set 
            {
                if (value == null)
                    throw new Exception("Не найдена запись в таблице каталогов!");
                _curRow = value; 
            }
        }

        private Util.ActionType _action;
        /// <summary>
        /// Цель, с которой открыта форма
        /// </summary>
        public Util.ActionType OpenAction
        {
            get { return _action; }
            set { _action = value; }
        }
        private int _catalogId;
        /// <summary>
        /// Идентификатор выбранной фармгруппы
        /// </summary>
        public int CatalogId
        {
            get { return _catalogId; }
            set { _catalogId = value; }
        }


        private CatalogDetails()
        {
            InitializeComponent();
            
        }
        public CatalogDetails(Util.ActionType actType,Int32 catId,Catalog parent)
        {
            InitializeComponent();
            OpenAction = actType;
            CatalogId = catId;
            _parent = parent;
        }
        public CatalogDetails(Util.ActionType actType, Int32 catId, DIProject.DataSets.Dictionary.CatalogDataTable catalogData)
        {
            InitializeComponent();
            this.OpenAction = actType;
            this.CatalogId = catId;
            this._catalogData = catalogData;
        }
        private void CatalogDetails_Load(object sender, EventArgs e)
        {
            InitCatalogList();
            switch (OpenAction)
            {
                case DIProject.Util.ActionType.Update:
                    InitUpdate();
                    break;
                case DIProject.Util.ActionType.Insert:
                    InitInsert();
                    break;
                default:
                    this.Close();
                    break;
            }
        }
        private void InitCatalogList()
        {
            cbCatList.ValueMember = "Id";
            cbCatList.DisplayMember = "Name";
            this.CatalogData.DefaultView.RowFilter = string.Empty;
            cbCatList.DataSource = this.CatalogData;
        }
        private void InitUpdate()
        {
            btnDelete.Visible = true;
            btnSaveUpdate.Text = "Изменить";
            this.CurrentRow = CatalogData.FindById(CatalogId);
            DIProject.DataSets.Dictionary.CatalogRow cr = CatalogData.FindById(CurrentRow.ParentId);
            Int32 pos = cbCatList.FindString(cr.Name);
            cbCatList.SelectedIndex = pos;
            txbName.Text = CurrentRow.Name;
            txbNote.Text = CurrentRow.Note;
            if (!CurrentRow.IsMarkUpNull())
                txbMarkUp.Text = CurrentRow.MarkUp.ToString();
            
        }
        private void InitInsert()
        {
            btnSaveUpdate.Text = "Сохранить";
            btnDelete.Visible = false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Вы действительно хотите удалить группу " + CurrentRow.Name + "?", "Удаление фармгруппы", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
               // DIProject.DataSets.Dictionary.CatalogDataTable cat = this.CatalogData;
                CurrentRow.Delete();
                DIProject.DataSets.DictionaryTableAdapters.CatalogTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.CatalogTableAdapter();
                adapter.Update(CatalogData);
                CatalogData.AcceptChanges();
                adapter.Fill(CatalogData, DIProject.Data.Sync.IsAdmin);
            }
            this.Close();
        }

        private void btnSaveUpdate_Click(object sender, EventArgs e)
        {
            DIProject.DataSets.DictionaryTableAdapters.CatalogTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.CatalogTableAdapter();
            if (OpenAction == DIProject.Util.ActionType.Insert)
            {
                DIProject.DataSets.Dictionary.CatalogRow cr = CatalogData.NewCatalogRow();
                cr.Name = txbName.Text;
                cr.Note = txbNote.Text;
                cr.ParentId = (Int32)cbCatList.SelectedValue;                
                cr.MD = DateTime.Now;
                cr.MW = FirstForm.Login;
                cr.ToDelete = false;
                
                CatalogData.Rows.Add(cr);
                adapter.Update(CatalogData);
                cr.Original_MD = cr.MD;
                cr.OriginalID = cr.Id;
                CatalogData.AcceptChanges();
            }
            else
                if (OpenAction == DIProject.Util.ActionType.Update)
                {
                    //CurrentRow.BeginEdit();
                    CurrentRow.Name = txbName.Text;
                    CurrentRow.Note = txbNote.Text;
                    CurrentRow.MarkUp = Convert.ToDouble(txbMarkUp.Text);
                    //adapter.u
                    CurrentRow.MD = DateTime.Now;
                    CurrentRow.ParentId = (Int32)cbCatList.SelectedValue;
                    CurrentRow.MW = FirstForm.Login;
                    CurrentRow.ToDelete = false;
                   // CurrentRow.EndEdit();
                    adapter.Update(CurrentRow);
                    CurrentRow.Original_MD = CurrentRow.MD;
                    CurrentRow.OriginalID = CurrentRow.Id;
                    CatalogData.AcceptChanges();                    
                }
                else
                {
                    this.Close();
                    return;
                }
           // object obj = this.Parent.GetType();
            this.Close();
            
        }

        private void txbMarkUp_Validating(object sender, CancelEventArgs e)
        {

        }

        private void txbMarkUp_KeyPress(object sender, KeyPressEventArgs e)
        {
            float f;
            if (e.KeyChar == '\b')
                return;
            if (!float.TryParse(txbMarkUp.Text + e.KeyChar, out f))
            {
                System.Console.Beep(500, 100);
                e.Handled = true;
            }
        }

        private void txbMarkUp_KeyDown(object sender, KeyEventArgs e)
        {
         //   char ch = (char)e.KeyValue;
         //   if ((char.IsDigit(ch)) || (ch == ','))
         //      return;
         //   System.Console.Beep(500, 100);
         //   e.Handled = true;            
        }
    }
}